﻿using System;
using System.Linq;
using System.Web;
using System.ServiceModel;
using System.ServiceModel.Activation;
using NetBay.Core.BusinessEntities;
using Rio.Applications.Web.Services;

namespace Rio.Applications.Web.RioServices
{
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public abstract class RioServicesBase
    {
        /// <summary>
        /// Gets the authenticate user.
        /// </summary>
        /// <value>The authenticate user.</value>
        private User AuthenticatedUser { get; set; }

        /// <summary>
        /// Gets or sets the domain service.
        /// </summary>
        /// <value>The domain service.</value>
        private BusinessEntitiesDomainService DomainService { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="RioService" /> class.
        /// </summary>
        public RioServicesBase()
        {
            DomainService = new BusinessEntitiesDomainService();
        }

        /// <summary>
        /// Performs the NTLM authentication.
        /// </summary>
        /// <returns></returns>
        public bool PerformNTLMAuthentication()
        {
            string UserName = HttpContext.Current.User.Identity.Name;
            if (UserName.Contains("\\"))
            {
                UserName = UserName.Substring(UserName.IndexOf(@"\") + 1, UserName.Length - UserName.IndexOf(@"\") - 1);
            }

            AuthenticatedUser = DomainService.GetAccess(UserName, "", 0).ToList().FirstOrDefault();
            if (AuthenticatedUser != null)
                return true;
            else
                return false;
        }

        /// <summary>
        /// Performs the rio authentication.
        /// </summary>
        /// <param name="UserName">Name of the user.</param>
        /// <param name="Password">The password.</param>
        /// <returns></returns>
        public bool PerformRioAuthentication(string UserName, string Password)
        {
            AuthenticatedUser = DomainService.GetAccess(UserName, Password, 1, false).ToList().FirstOrDefault();
            if (AuthenticatedUser != null)
                return true;
            else
                return false;
        }

        /// <summary>
        /// Sets the actual context.
        /// </summary>
        protected void SetContextState()
        {
            if (AuthenticatedUser == null)
            {
                throw new Exception("Unauthenticated User!");
            }
            if (HttpContext.Current.Session[ParameterSession.CurrentUser.szGetDescription()] == null)
            {
                HttpContext.Current.Session[ParameterSession.CurrentUser.szGetDescription()] = AuthenticatedUser;
            }
        }

    }
}